#include "ScreenQuadParser.h"

#include "..\utils\Log.h"
#include "..\utils\PlainTextReader.h"
#include "..\base\Engine.h"
#include "..\game\World.h"
#include "..\addons\ScreenQuad.h"

namespace ds {

void ScreenQuadDecl::createResource() {
	ScreenQuad* sq = new ScreenQuad(m_NodeName,m_Material,m_Vertices,false);
	for ( size_t i = 0; i < m_Quads.size(); ++i ) {
		QuadDecl* qd = &m_Quads[i];
		sq->add(qd->pos.x,qd->pos.y,qd->size.x,qd->size.y,qd->rect);
	}
	gEngine->getWorld().attachNode(sq,m_Layer.c_str());
}

ResourceDeclaration* ScreenQuadParser::loadTextFile(const ResourceFile& resourceFile) {
	PlainTextReader reader;
	if ( reader.readFile(resourceFile.fqName.c_str()) ) {
		Category* root = reader.getRoot();		
		std::string nodeName = root->getProperty("name");
		std::string material = root->getProperty("material");
		std::string layer = root->getProperty("layer");
		int vertices = root->read<int>("vertices",512);
		ScreenQuadDecl* decl = new ScreenQuadDecl(nodeName,material,layer,vertices);		
		std::vector<Category*> categories = root->getChildren();
		for ( size_t i = 0; i < categories.size(); ++i ) {
			Category* cat = categories[i];
			if ( cat->getName() == "quad" ) {
					Vec2 pos = cat->getVec2("pos");
					Vec2 size = cat->getVec2("size");
					Rect rect = cat->getRect("texture_rect");
					decl->addQuad(pos,size,rect);
			}
		}
		
		return decl;
	}
	return 0;
}

void ScreenQuadParser::createResource(ResourceDeclaration* declaration) {
	ScreenQuadDecl* decl = static_cast<ScreenQuadDecl*>(declaration);
	decl->createResource();
}

}